import {getPageProducts} from '@/api/ShopDatabase/index.js'
import {getBaseSetting} from '@/api/ShopDatabase/goodsSetting'
import {changeOptions,getFieldValue} from '@/utils/common'
import { useDistInfoStore } from '@/stores/dict.js'
const dictStore = useDistInfoStore()

const seachTableRef = ref(null)
const typeOptions = ref([]) //产品类别
const brandOptions = ref(dictStore.getDistInfo('经营品牌').map(item=>({label:item.permissionName,value:item.id}))) //经营品牌
const unitOptions = ref([]) //单位
const salesClassOptions = ref([]) //销售分类
const wayUseOptions = ref([]) //使用途径
const frequencyUseOptions = ref([]) //使用频率
const wholesaleClassOptions = ref([]) //批发分类
export const getOptions = async (callBack)=>{
  const res = await getBaseSetting()
  typeOptions.value = getFieldValue('类别',res,'id')
  unitOptions.value = getFieldValue('单位',res,)
  salesClassOptions.value = getFieldValue('销售分类',res,'id')
  wayUseOptions.value = getFieldValue('使用途径',res,)
  frequencyUseOptions.value = getFieldValue('使用频率',res,)
  wholesaleClassOptions.value = getFieldValue('批发分类',res,)
  callBack && callBack()
}

export const useCommonData = () => {
  return {
    seachTableRef,
    typeOptions,
    brandOptions,
    unitOptions,
    salesClassOptions,
    wayUseOptions,
    frequencyUseOptions,
    wholesaleClassOptions,
  }
}
export const useCurd = (props) => {
  getOptions(setOptions)
  const router = useRouter();

  // 表格数据
  const tableLoading = ref(false)
  const totalPage = ref(0)
  const tableData = ref([])

  // 搜索
  const handlerSearch = async (data) => {
    try{
      tableLoading.value = true
      data.businessBrandId = data?.businessBrandId?.join(',') ?? ''
      const res = await getPageProducts(data)
      tableData.value = res.records
      totalPage.value = +res.total
    }finally{
      tableLoading.value = false
    }
  }
  const openEditDialog = (row = {}) => {
    if(row?.id){
      // 编辑
      router.push({name:'ProductManagementEdit',query:{id:row.id}})
    }else{
      router.push({name:'ProductManagementAdd'})
    }
  }

  /**表格配置start */
  const btnLefts = [
    {
      label:'新增产品',
      type:'primary',
      show:()=>true,
      img:new URL("@/assets/icon/btn-add.png",import.meta.url),
      click:(row)=>{
        openEditDialog()
      }
    },
  ]
  const btnRights = []
  const tableConfig = ref([
    {
      type:'slot',
      label:'产品编号',
      prop:'code',
      width:150,
      slotName:'productCode'
    },
    {
      type:'slot',
      label:'产品名称',
      prop:'productName',
      width:296,
      textOverflow:true,
      slotName:'productName'
    },
    {
      label:'类别',
      prop:'category',
      width:74
    },
    {
      label:'经营品牌',
      prop:'businessBrandId',
      width:100,
      format:(value)=> {
        value = value?.split(',')
        return value.map(item=>brandOptions.value.find(brand=>brand.value===item)?.label).join('、')
      }
    },
    {
      label:'销售分类',
      prop:'salesClass',
      width:100
    },
    {
      label:'零售价',
      prop:'retailPrice',
      width:90
    },
    {
      label:'批发价',
      prop:'wholesaleInfoPrice',
      width:90
    },
    {
      label:'执行标准',
      prop:'carriedStandard',
      width:110
    },
    {
      label:'产地',
      prop:'origin',
      width:70
    },
    {
      label:'销售状态',
      prop:'salesState',
      width:100,
      format:(value)=> +value===1 ? '正常' : '停售'
    },
    {
      label:'允许上架商城',
      prop:'mallInfoPut',
      width:120,
      format:(value)=> +value===1 ? '允许' : '不允许'
    },
    {
      label:'首页展示',
      prop:'showIndex',
      type:'slot',
      width:120,
      slotName:'homePageDisplay'
    },
    {
      label:'配送方式',
      prop:'pickType',
      width:120,
      format:(value)=> {
        return ['','外卖配送','用户自提','快递配送'][value] || '-'
      }
    },
    {
      label:'批发状态',
      prop:'wholesaleInfoState',
      width:100,
      format:(value)=> +value===1 ? '正常' : '停发'
    },
    {
      label:'创建人',
      prop:'createByName',
      width:88
    },
    {
      label:'创建时间',
      prop:'createTime',
      width:200
    },
    {
      label:'最近更新',
      prop:'updateTime',
      width:200
    },
    {
      type: "action",
      label:'操作',
      prop:'name',
      fixed: "right",
      width: 200,
      btns:[
        {
          label:()=>'编辑',
          type:'success',
          show:(row)=>true,
          click:(row)=>{
            openEditDialog(row)
          }
        },
        {
          label:()=>'查看',
          type:'primary',
          show:(row)=>true,
          click:(row)=>{
            router.push({name:'ProductManagementDetail',query:{id:row.id}})
          }
        }
      ]
    }
  ])
  const tableForms = ref([
    {
      type: "datePicker",
      prop: ["startDate", "endDate"],
      startPlaceholder: "创建开始时间",
      endPlaceholder: "创建结束时间",
      label: "",
      model: [],
    },
    {
      type: "input",
      prop: 'fuzzyValue',
      placeholder: "产品名称/编号/助记码/条码",
      label: "",
      model: '',
    },
    {
      type: "select",
      placeholder: "类别",
      label: '',
      filterable:true,
      prop: 'categoryId',
      data:[],
      model: "",
    },
    {
      type: "select",
      filterable:true,
      multiple:true,
      placeholder: "经营品牌",
      label: '',
      prop: 'businessBrandId',
      data:[],
      model: '',
    },
    {
      type: "select",
      placeholder: "销售状态",
      label: '',
      prop: 'salesState',
      data:[
          {
            label:"正常",
            value:1
          },
          {
            label:'停售',
            value:2
          }
      ],
      model: "",
    },
    {
      type: "select",
      placeholder: "允许上架商城",
      label: '',
      prop: 'mallInfoPut',
      data:[
          {
            label:"允许",
            value:1
          },
          {
            label:'不允许',
            value:2
          }
      ],
      model: "",
    },
    {
      type: "select",
      placeholder: "销售分类",
      label: '',
      filterable:true,
      prop: 'salesClassIdList',
      data:[],
      multiple:true,
      model: [],
    },
    {
      type: "input",
      prop: 'createByName',
      placeholder: "创建人",
      label: "",
      model: '',
    },
    {
      type: "select",
      placeholder: "首页展示",
      label: '',
      prop: 'showIndex',
      data:[{
        label:"展示",
        value:1
      },
      {
        label:"不展示",
        value:0
      }],
      model: [],
    },
  ])
  function setOptions(){
    changeOptions(tableForms,['categoryId','salesClassIdList','businessBrandId'],[typeOptions.value,salesClassOptions.value,brandOptions.value])
  }
  /**表格配置end */
  return {
    tableLoading,
    totalPage,
    tableData,
    btnLefts,
    btnRights,
    tableConfig,
    tableForms,
    handlerSearch,
    seachTableRef
  }
}